package com.marisfrolg.storage;

import java.lang.ref.WeakReference;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

import com.beardedhen.androidbootstrap.BootstrapButton;
import com.beardedhen.androidbootstrap.BootstrapEditText;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.exception.DbException;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.lidroid.xutils.view.annotation.event.OnKey;
import com.marisfrolg.base.BaseApplication;
import com.marisfrolg.controller.InbItemSubControl;
import com.marisfrolg.entity.VoucherInb;
import com.marisfrolg.entity.json.Inb;
import com.marisfrolg.entity.json.InbItem;
import com.marisfrolg.entity.json.InbItemSub;
import com.marisfrolg.entity.json.InbResult;
import com.marisfrolg.entity.json.InbResultDetail;
import com.marisfrolg.entity.json.InbSub;
import com.marisfrolg.entity.json.User;
import com.marisfrolg.util.ReadCodeController;
import com.marisfrolg.util.StringUtil;
import com.marisfrolg.util.WebServicesUtil;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.util.SparseArray;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnKeyListener;
import android.view.View.OnTouchListener;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

public class BackbinActivity extends ItemActivity {
	private WSHandler wHandler;
	private WebServicesUtil ws;
	private LayoutInflater inflater;
	@ViewInject(R.id.voucheredit)
	BootstrapEditText voucheredit;
	@ViewInject(R.id.productnoedit)
	BootstrapEditText productnoedit;
	@ViewInject(R.id.submit)
	BootstrapButton submit;
	@ViewInject(R.id.showresult)
	BootstrapButton showresult;
	@ViewInject(R.id.proList)
	LinearLayout proList;
	@ViewInject(R.id.total)
	TextView total;
	@ViewInject(R.id.picktotal)
	TextView picktotal;
	@ViewInject(R.id.automode)
	private Switch autoSwitch;
	@ViewInject(R.id.tasklistscroll)
	private ScrollView scrollView;
	private VoucherInb vi;
	private final static String READCODEVALUE="READCODEVALUE";
	private final static String FOCUSVIEW="FOCUSVIEW";
	private final static int AUTOREAD=3010;
	private final static int SCROLLDOWN=-333;
	private int itemmargin=10;
	private InbItemSubControl isControl;
	private ReadCodeController rcc; 
	private String lastestProNo="";
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_backbin);
		inflater=LayoutInflater.from(this);
		ViewUtils.inject(this);
		sHandler=new ScanHandler(this);
		wHandler=new WSHandler(this);
		ws=new WebServicesUtil(this,wHandler);
		rcc=((BaseApplication)getApplication()).getReadCodeController();
		rcc.setHandler(sHandler);
		rcc.Open();
		isControl=new InbItemSubControl(db);
		try {
			vi=db.findFirst(VoucherInb.class);
		} catch (DbException e) {
			e.printStackTrace();
		}
		if(vi!=null){
			voucheredit.setEnabled(false);
			voucheredit.setText(vi.getVoucherno());
		}
		refresh();
	}
	@OnClick(R.id.automode)
	public void changeMode(View v){
		play_sound(true);
	}
	@OnKey(R.id.voucheredit)//完成凭证号
	public void voucherFinish(View v, int keyCode, KeyEvent event){	
		if(keyCode==KeyEvent.KEYCODE_ENTER&&event.getAction()==KeyEvent.ACTION_UP){
			String code=voucheredit.getText().toString().trim().toUpperCase(Locale.US);
			voucheredit.setText("");
			Message msg=new Message();
			msg.what=ReadCodeController.CODEREAD;
			Map<String,Object> params=new HashMap<String, Object>();
			params.put(READCODEVALUE, code);
			params.put(FOCUSVIEW, v);
			msg.obj=params;
			sHandler.dispatchMessage(msg);
		}
	}
	@OnKey(R.id.productnoedit)//完成款号
	public void productFinish(View v, int keyCode, KeyEvent event){	
		if(keyCode==KeyEvent.KEYCODE_ENTER&&event.getAction()==KeyEvent.ACTION_UP){
			String code=productnoedit.getText().toString().trim().toUpperCase(Locale.US);
			productnoedit.setText("");
			Message msg=new Message();
			msg.what=ReadCodeController.CODEREAD;
			Map<String,Object> params=new HashMap<String, Object>();
			params.put(READCODEVALUE, code);
			params.put(FOCUSVIEW, v);
			msg.obj=params;
			sHandler.dispatchMessage(msg);
		}
	}
	@OnClick(R.id.changeproduct)
	public void changeproduct(View v){
		new AlertDialog.Builder(this).setPositiveButton("确定", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				try {
					productnoedit.setText("");
					db.deleteAll(InbSub.class);
					db.deleteAll(InbItemSub.class);
					db.deleteAll(InbResultDetail.class);
					play_sound(true);
					refresh();
					productnoedit.requestFocus();
				} catch (DbException e) {
					e.printStackTrace();
				}
			}
		}).setNegativeButton("取消", null).setTitle("提示").setMessage("是否重新输入款号").show();
	}
	@OnClick(R.id.changevoucher)
	public void changevoucher(View v){
		new AlertDialog.Builder(this).setPositiveButton("确定", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				try {
					db.deleteAll(VoucherInb.class);
					db.deleteAll(InbItem.class);
					db.deleteAll(InbSub.class);
					db.deleteAll(InbItemSub.class);
					db.deleteAll(InbResultDetail.class);
					play_sound(true);
					voucheredit.setEnabled(true);
					voucheredit.setText("");
					productnoedit.setEnabled(true);
					productnoedit.setText("");
					refresh();
					voucheredit.requestFocus();
				} catch (DbException e) {
					e.printStackTrace();
				}
			}
		}).setNegativeButton("取消", null).setTitle("提示").setMessage("是否重新输入凭证(将清空界面)").show();
	}
	//拆分
	public void split(int inbid){
		final int i=inbid;
		if(isControl.getSurplusByInbid(inbid)<=0){
			Toast.makeText(this, "已完成无法拆分", Toast.LENGTH_SHORT).show();
			return;
		}
		final EditText et=new EditText(this);
		int preNum=isControl.getTotalSumByInbid(i)-isControl.getSumByInbid(i);
		et.setText(preNum>0?preNum+"":0+"");
		et.selectAll();
		new AlertDialog.Builder(this).setPositiveButton("确定", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				try {
					int pre=Integer.parseInt((et.getText()+"").trim());
					String bin="";
					if(autoSwitch.isChecked()&&(!StringUtil.isEmpty(lastestProNo))){
						bin=lastestProNo;
					}
					isControl.spilt(i,pre,bin);
					play_sound(true);
					refresh();
				} catch (NumberFormatException e) {
					Toast.makeText(BackbinActivity.this, "输入正确的数字", Toast.LENGTH_SHORT).show();
				}
			}
		}).setNegativeButton("取消", null).setView(et).setTitle("提示").setMessage("输入拆分出来数量:").show();
	}
	//删除单项
	public void delete(int id){
		final int i=id;
		new AlertDialog.Builder(this).setPositiveButton("确定", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				isControl.delete(i);
				play_sound(true);
				refresh();
			}
		}).setNegativeButton("取消", null).setTitle("提示").setMessage("将移除此项目").show();
	}
	//查看错误
	@OnClick(R.id.showresult)
	public void showresult(View v){
		try {
			List<InbResultDetail>irdlist=db.findAll(InbResultDetail.class);
			if(irdlist==null){
				return;
			}
			String errmsg="";
			for (InbResultDetail ird : irdlist) {
				if(!"0".equals(ird.SUBRC)){
					errmsg+=ird.getPRODUCTNO()+"-> "+ird.MEG_ERR+"+;code:+"+ird.SUBRC+"\n"; 
				}
			}
			Toast.makeText(this, errmsg, Toast.LENGTH_LONG).show();
		} catch (Exception e) {//DbException
			e.printStackTrace();
		}
	}
	//提交
	@OnClick(R.id.submit)
	public void submit(View v){
		try {
			vi=db.findFirst(VoucherInb.class);
			if(vi==null){
				return;
			}
			if(StringUtil.isEmpty(vi.getVoucherno())){
				Toast.makeText(this, "没有凭证", Toast.LENGTH_SHORT).show();
				return;
			}
			if(!isControl.isAllCheck()){
				Toast.makeText(this, "项目没有全部确认", Toast.LENGTH_SHORT).show();
				play_sound(false);
				return;
			}
			SparseArray<String> map=isControl.getCutMap();
			int ne=0;
			int na=0;
			for(int i=0;i<map.size();i++){
				int j=map.keyAt(i);
				if(j<0){
					ne=j;
				}
				if(j>0){
					na=j;
				}
			}
			if(ne<0){
				Toast.makeText(this, "订单没有足够的数量,"+map.get(na)+" 有多余", Toast.LENGTH_LONG).show();
				play_sound(false);
				return;
			}else{
				String msg="确认提交?";
				if(na>0){
//					msg="提交数量为:"+isControl.getConfirmSum()+";共:"+isControl.getTotalSum()+".是否确认提交?";
					Toast.makeText(this, "订单数量不正确, "+map.get(na)+" 不完整", Toast.LENGTH_LONG).show();
					play_sound(false);
					return;
				}
				new AlertDialog.Builder(this).setPositiveButton("确定", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						try {
							InbSub is=new InbSub();
							List<List<InbItemSub>>tlist=new ArrayList<List<InbItemSub>>();
							Set<Integer> inbids=new HashSet<Integer>();
							List<InbItemSub>list=db.findAll(InbItemSub.class);
							for (InbItemSub inbItemSub : list) {
								inbids.add(inbItemSub.getInbId());
							}
							list=null;
							for (Integer inbid : inbids) {
								List<InbItemSub>ls=db.findAll(Selector.from(InbItemSub.class).where("inbid", "=", inbid));
								for(int i=0;i<ls.size();i++){
									InbItemSub ii=ls.get(i);
									ii.TAPOS=i+1;
									if(i==ls.size()-1){
										ii.SPLIT="";
									}
								}
								tlist.add(ls);
							}
							is.setITEM_DETAIL(tlist);
							HashMap<String , Object> params=new HashMap<String, Object>();
							Gson gson=new Gson();
							Type type = new TypeToken<User>() {}.getType();
							Type typeis = new TypeToken<InbSub>() {}.getType();
							params.put("SUBINBOUND", gson.toJson(is, typeis));
							params.put("USER", gson.toJson(loginUser, type));
							progressDialog = ProgressDialog.show(BackbinActivity.this, "查询中", "请稍候...", true, true);
							progressDialog.setCanceledOnTouchOutside(false);
							progressDialog.setOnCancelListener(new OnCancelListener() {
								public void onCancel(DialogInterface dialog) {
									WebServicesUtil.setConnectionTimeOut();
								}
							});
							ws.call(WebServicesUtil.ACTION_submitINBOUND, params, WebServicesUtil.URL_ACTION_submitINBOUND, WebServicesUtil.METHOD_ACTION_submitINBOUND);
						} catch (DbException e) {
							e.printStackTrace();
						}
					}
				}).setNegativeButton("取消", null).setTitle("提示").setMessage(msg).show();
			}
		} catch (DbException e) {
			e.printStackTrace();
		}
	}
	
	@OnClick(R.id.vouchertitle)
	public void test(View v){
		try {
			List<InbItem> list=db.findAll(InbItem.class);
			String msg="";
			if(list!=null){
				for (InbItem inbItem : list) {
					msg+=inbItem.toString();
				}
			}
			Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
		} catch (DbException e) {
			e.printStackTrace();
		}
		
	}
	@OnClick(R.id.guicang)
	public void test2(View v){
		test(v);
	}
	
	private void refreshTotal(){
		try {
			List<InbResultDetail> irs=db.findAll(InbResultDetail.class);
			if(irs!=null){
				boolean su=true;
				for (InbResultDetail ird : irs) {
					su=su&&("0".equals(ird.SUBRC));
				}
				if(su){
					showresult.setBootstrapType("default");
				}else{
					showresult.setBootstrapType("danger");
				}
			}
			total.setText("订单未归总数量: "+isControl.getTotalSum());
			int x=isControl.getConfirmSum();
			int y=isControl.getPickTotalSum();
			SpannableStringBuilder style=new SpannableStringBuilder("已确认:"+x+"个,共"+y+"个");
			int end=(x+"").length();
			if(x==y){
				style.setSpan(new ForegroundColorSpan(Color.GREEN),4,4+end,Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
			}else{
				style.setSpan(new ForegroundColorSpan(Color.RED),4,4+end,Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
			}
			picktotal.setText(style);
		} catch (DbException e) {
			e.printStackTrace();
		}
		goToEdit();
	}
	
	public void refresh(){
		proList.removeAllViews();
		try {
			vi=db.findFirst(VoucherInb.class);
			if(vi==null){
				refreshTotal();
				return;
			}
			//设置数量监听
			OnClickListener itemListener=new OnClickListener() {
				public void onClick(View v) {
					TextView idtv=(TextView)((RelativeLayout)v.getParent().getParent()).findViewById(R.id.id);
					TextView inbidtv=(TextView)((RelativeLayout)v.getParent().getParent()).findViewById(R.id.inbid);
					final int id=Integer.parseInt((idtv.getText()+"").trim());
					final int inbid=Integer.parseInt((inbidtv.getText()+"").trim());
					switch(v.getId()){
					case R.id.qtyedit://数量设置
						final EditText et=new EditText(BackbinActivity.this);
						et.setText(isControl.getSurplusByInbid(inbid)+"");
						et.selectAll();
						new AlertDialog.Builder(BackbinActivity.this).setView(et).setPositiveButton("确定", new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int which) {
								try {
									InbItemSub iis=db.findFirst(Selector.from(InbItemSub.class).where("id", "=", id));
									iis.setQTY(Integer.parseInt((et.getText()+"").trim()));
									db.update(iis, "qty");
									refresh();
									play_sound(true);
								} catch (Exception e) {
									e.printStackTrace();
									Toast.makeText(BackbinActivity.this, "输入正确的数字", Toast.LENGTH_LONG).show();
								}
							}
						}).setNegativeButton("取消", null).setTitle("提示").setMessage("输入数量:").show();
						break;
					case R.id.split://拆分
						split(inbid);
						break;
					case R.id.delete://删除
						delete(id);
						break;
					default:break;
					}
					refresh();
				}
			};
			//设置仓位
			OnFocusChangeListener oal=new OnFocusChangeListener(){
				public void onFocusChange(View v, boolean hasFocus) {
					BootstrapEditText bet;
					if(hasFocus){//获取焦点
						
					}else if((!hasFocus)&&v.getId()==R.id.binedit){//仓位框失去焦点提交仓位
						bet=(BootstrapEditText)v;
						if(!StringUtil.isEmpty(bet.getText()+"")){
							Message msg=new Message();
							Map<String,Object> params=new HashMap<String, Object>();
							params.put(READCODEVALUE, bet.getText()+"");
							params.put(FOCUSVIEW, v);
							msg.obj=params;
							msg.what=ReadCodeController.CODEREAD;
							sHandler.dispatchMessage(msg);
						}
					}
				}
			};
			//swich监听
			OnTouchListener otl=new OnTouchListener() {
				public boolean onTouch(View v, MotionEvent event) {
					if(event.getAction()==MotionEvent.ACTION_DOWN){
						return touchEvent(v);
					}
					return false;
				}
			};
			List<InbItemSub> list=db.findAll(Selector.from(InbItemSub.class).orderBy("productno,id"));
			int size=list.size();
			int i=1;
			for (InbItemSub inbItemSub : list) {
				View bbitem = inflater.inflate(R.layout.backbin_item, null);
				proList.addView(bbitem);
				LinearLayout.LayoutParams layoutParams=(LinearLayout.LayoutParams)bbitem.getLayoutParams();
				layoutParams.topMargin=itemmargin;
				//序号
				TextView seq=(TextView)bbitem.findViewById(R.id.seqhao);
				seq.setText(i+"");
				i++;
				//ID设置
				TextView idtv=(TextView)bbitem.findViewById(R.id.id);
				TextView inbidtv=(TextView)bbitem.findViewById(R.id.inbid);
				idtv.setText(inbItemSub.getId()+"");
				inbidtv.setText(inbItemSub.getInbId()+"");
				//数量
				BootstrapEditText qty=(BootstrapEditText)bbitem.findViewById(R.id.qtyedit);
				qty.setText(inbItemSub.QTY+"");
				qty.setOnClickListener(itemListener);
				qty.setEnabled(!inbItemSub.isCheckQTY());
				//总数
				TextView total=(TextView)bbitem.findViewById(R.id.total);
				total.setText(inbItemSub.getTotal());
				//款号
				TextView product=(TextView)bbitem.findViewById(R.id.kuanhao);
				product.setText(inbItemSub.PRODUCTNO);
				//仓位类型
				TextView ltype=(TextView)bbitem.findViewById(R.id.ltype);
				ltype.setText(inbItemSub.getLTYPT());
				//仓位号
				BootstrapEditText binedit=(BootstrapEditText)bbitem.findViewById(R.id.binedit);
				binedit.setText(inbItemSub.getSTOBIN());
				if(!StringUtil.isEmpty(inbItemSub.getSTOBIN())){
					bbitem.setBackgroundResource(R.drawable.item_bg_blue);
				}
				binedit.setEnabled(!inbItemSub.isCheckQTY());
				binedit.setOnFocusChangeListener(oal);
				//确认开关
				Switch check=(Switch)bbitem.findViewById(R.id.check);
				check.setChecked(inbItemSub.isCheckQTY());
				if(inbItemSub.isCheckQTY()){
					bbitem.setBackgroundResource(R.drawable.item_bg_green1);
				}
				check.setOnTouchListener(otl);
				//拆分,删除监听
				BootstrapButton split=(BootstrapButton)bbitem.findViewById(R.id.split);
				BootstrapButton delete=(BootstrapButton)bbitem.findViewById(R.id.delete);
				split.setOnClickListener(itemListener);
				delete.setOnClickListener(itemListener);
				//最后一个控件的下一个焦点是提交按钮
				if(size==inbItemSub.getTAPOS()){
					binedit.setOnKeyListener(new OnKeyListener() {
						public boolean onKey(View v, int keyCode, KeyEvent event) {
							if(keyCode==KeyEvent.KEYCODE_ENTER&&event.getAction()==KeyEvent.ACTION_DOWN){
								BootstrapEditText bet=(BootstrapEditText)v;
								if(!StringUtil.isEmpty(bet.getText()+"")){
									Message msg=new Message();
									Map<String,Object> params=new HashMap<String, Object>();
									params.put(READCODEVALUE, bet.getText()+"");
									params.put(FOCUSVIEW, v);
									msg.obj=params;
									msg.what=ReadCodeController.CODEREAD;
									sHandler.dispatchMessage(msg);
								}
							}
							return false;
						}
					});
				}
			}
		} catch (DbException e) {
			e.printStackTrace();
		}
		refreshTotal();
		sHandler.sendEmptyMessage(SCROLLDOWN);
	}

	//根据扫描code处理数据
	public void readcode(String code,View view,boolean sout) throws DbException{
		code=code.toUpperCase(Locale.US).trim();
		if(StringUtil.isEmpty(code)){
			return;
		}
		View v=getCurrentFocus();
		if(v==null||v.getId()==R.id.confirm){//无焦点时,找到最近一次操作的焦点
			v=view;
			if(v==null){
				return;
			}
		}
		switch (v.getId()) {
		case R.id.voucheredit:
			vi=db.findFirst(VoucherInb.class);
			if(vi!=null&&(!StringUtil.isEmpty(vi.getVoucherno()))){
				return;
			}
			HashMap<String , Object> params=new HashMap<String, Object>();
			params.put("INBOUND", code);
			Gson gson=new Gson();
			Type type = new TypeToken<User>() {}.getType();
			params.put("USER", gson.toJson(loginUser, type));
			progressDialog = ProgressDialog.show(this, "查询中", "请稍候...", true, true);
			progressDialog.setCanceledOnTouchOutside(false);
			progressDialog.setOnCancelListener(new OnCancelListener() {
				public void onCancel(DialogInterface dialog) {
					WebServicesUtil.setConnectionTimeOut();
				}
			});
			ws.call(WebServicesUtil.ACTION_getINBOUND, params, WebServicesUtil.URL_ACTION_getINBOUND, WebServicesUtil.METHOD_ACTION_getINBOUND);
			break;
		case R.id.productnoedit:
			InbItem inbItem=db.findFirst(Selector.from(InbItem.class).where("productno", "=", code));
			if(inbItem==null){
				play_sound(false);
				Toast.makeText(this, "此凭证下无此款号:"+code, Toast.LENGTH_LONG).show();
				productnoedit.setText("");
				productnoedit.requestFocus();
				break;
			}else if("X".equals(inbItem.getCO())){
				play_sound(false);
				Toast.makeText(this, "此款号任务已完结:"+code, Toast.LENGTH_LONG).show();
				productnoedit.setText("");
				productnoedit.requestFocus();
				break;
			}
			vi=db.findFirst(VoucherInb.class);
			if(vi==null){
				break;
			}
			InbItemSub inbItemSub=new InbItemSub(inbItem);
			vi.setProductsum(inbItem.getQTY());
			db.update(vi, "productno","productsum");
			if(autoSwitch.isChecked()&&(!StringUtil.isEmpty(lastestProNo))){
				inbItemSub.setSTOBIN(lastestProNo);
				inbItemSub.setCheckQTY(true);
			}
			db.saveBindingId(inbItemSub);
			play_sound(true);
			productnoedit.setText(code);
			refresh();
			break;
		case R.id.binedit:
			if(!StringUtil.isBin(code)){
				play_sound(false);
				Toast.makeText(this, "输入的不是仓位号", Toast.LENGTH_LONG).show();
				break;
			}
			if(autoSwitch.isChecked()){
				lastestProNo=code;
			}
			RelativeLayout rl=(RelativeLayout)v.getParent().getParent();
			TextView seqhao=(TextView)rl.findViewById(R.id.id);
			InbItemSub iis=db.findFirst(Selector.from(InbItemSub.class).where("id", "=", (seqhao.getText()+"").trim()));
			if(!code.equals(iis.getSTOBIN())){
				iis.setSTOBIN(code);
				db.update(iis, "stobin");
				BootstrapEditText binedit=(BootstrapEditText)v;
				binedit.setText(code);
				rl.setBackgroundResource(R.drawable.item_bg_blue);
				Switch check=(Switch)rl.findViewById(R.id.check);
				touchEvent(check);//输入仓位自动确认
				check.setChecked(true);
			}
			break;
		default:
			break;
		}
	}
	private void jsonToDb(Inb inb){
		try {
			vi=new VoucherInb();
			vi.setVoucherno(inb.getINBOUND());
			db.deleteAll(VoucherInb.class);
			db.deleteAll(InbItem.class);
			db.deleteAll(InbSub.class);
			db.saveBindingId(vi);
			db.saveAll(inb.getINBITEMS());
		} catch (DbException e) {
			e.printStackTrace();
		}
	}
	private void jsonResultToDb(InbResult ir){
		try {
			db.deleteAll(InbResultDetail.class);
			db.saveAll(ir.getDETAILS());
			showresult.setBootstrapType("danger");
		} catch (DbException e) {
			e.printStackTrace();
		}
	}
	
	private static class WSHandler extends Handler {
		WeakReference<BackbinActivity> wactivity;
		WSHandler(BackbinActivity activity) {
			wactivity = new WeakReference<BackbinActivity>(activity);
		}
		public void handleMessage(Message msg) {
			BackbinActivity activity = wactivity.get();
			switch (msg.what) {
			case WebServicesUtil.ACTION_getINBOUND:{
				if((msg.obj+"").startsWith("错误")){
					activity.play_sound(false);
					Toast.makeText(activity, msg.obj+"", Toast.LENGTH_LONG).show();
					activity.goToEdit();
					break;
				}
				Gson gson = new Gson();
				Type type = new TypeToken<Inb>() {}.getType();
				Inb inb=gson.fromJson(msg.obj+"", type);
				activity.jsonToDb(inb);
				activity.voucheredit.setText(inb.getINBOUND());
				activity.voucheredit.setEnabled(false);
				activity.play_sound(true);
				activity.productnoedit.requestFocus();
				activity.refreshTotal();
				break;
			}
			case WebServicesUtil.ACTION_submitINBOUND:{
				if((msg.obj+"").startsWith("错误")){
					activity.play_sound(false);
					Toast.makeText(activity, msg.obj+"", Toast.LENGTH_LONG).show();
					break;
				}
				Gson gson = new Gson();
				Type type = new TypeToken<InbResult>() {}.getType();
				InbResult ir=gson.fromJson(msg.obj+"", type);
				boolean su=true;
				for(InbResultDetail ird:ir.getDETAILS()){
					su=su&&("0".equals(ird.SUBRC));
				}
				if(su){
					activity.play_sound(true);
					activity.submitSuccess(ir);
					new AlertDialog.Builder(activity).setPositiveButton("确定", null).setTitle("提示").setMessage("处理成功").show();	
				}else{
					activity.play_sound(false);
					activity.jsonResultToDb(ir);
					String errmsg="";
					for (InbResultDetail ird : ir.getDETAILS()) {
						errmsg+=ird.getPRODUCTNO()+"-> "+ird.MEG_ERR+"\n";
					}
					new AlertDialog.Builder(activity).setPositiveButton("确定", null).setTitle("失败").setMessage("处理失败:\n"+errmsg).show();
				}
				break;
			}
			case WebServicesUtil.TIMEOUT:{
				if(activity.progressDialog!=null&&activity.progressDialog.isShowing()){
					activity.progressDialog.dismiss();
					new AlertDialog.Builder(activity).setPositiveButton("确定", null).setTitle("提示").setMessage("连接超时").show();
				}
				break;
			}
			case WebServicesUtil.NETUNREACHABLE:{
				Toast.makeText(activity, "网络无法连接或连接已取消,请稍后再试", Toast.LENGTH_SHORT).show();
				break;
			}
			default:
				break;
			}
			if(activity.progressDialog!=null&&activity.progressDialog.isShowing()){
				activity.progressDialog.dismiss();
			}
		}
	}
	
	private static class ScanHandler extends Handler {
		WeakReference<BackbinActivity> wactivity;
		ScanHandler(BackbinActivity activity) {
			wactivity = new WeakReference<BackbinActivity>(activity);
		}
		@SuppressWarnings("unchecked")
		public void handleMessage(Message msg) {
			BackbinActivity activity = wactivity.get();
			switch (msg.what) {
			case ReadCodeController.CODEREAD:{
				HashMap<String, Object>params;
				if(msg.obj instanceof String){
					params=new HashMap<String, Object>();
					params.put(READCODEVALUE, msg.obj);
				}else{
					params=(HashMap<String, Object>)msg.obj;
				}
				try {
					activity.readcode(params.get(READCODEVALUE)+"",(View)params.get(FOCUSVIEW),msg.arg1!=AUTOREAD);
				} catch (DbException e) {
					e.printStackTrace();
				}
				break;
			}
			case SCROLLDOWN:
				activity.scrollView.fullScroll(ScrollView.FOCUS_DOWN);
				break;
			default:
				break;
			}
		}
	};
	
	public void goToEdit(){
		if(StringUtil.isEmpty(voucheredit.getText()+"")){
			voucheredit.requestFocus();
			return;
		}else if(StringUtil.isEmpty(productnoedit.getText()+"")){
			productnoedit.requestFocus();
			return;
		}
		for(int i=0;i<proList.getChildCount();i++){
			RelativeLayout rl=(RelativeLayout)proList.getChildAt(i);
			BootstrapEditText binedit=(BootstrapEditText)rl.findViewById(R.id.binedit);
			if(StringUtil.isEmpty(binedit.getText()+"")){
				binedit.requestFocus();
				return;
			}
		}
	}

	
	public void submitSuccess(InbResult ir) {
		try {
			vi=db.findFirst(VoucherInb.class);
			db.deleteAll(InbSub.class);
			db.deleteAll(InbItemSub.class);
			for (InbResultDetail ird : ir.getDETAILS()) {
				InbItem ii=db.findFirst(Selector.from(InbItem.class).where("productno", "=", ird.getPRODUCTNO()));
				if(ii!=null){
					ii.setCO("X");
				}
				db.update(ii, "co");
			}
			db.deleteAll(InbResultDetail.class);
			productnoedit.setText("");
			refresh();
			productnoedit.requestFocus();
		} catch (DbException e) {
			e.printStackTrace();
		}
		
	}
	public void play_sound(boolean success) {
		try {
			if(success){
				mediaPlayer = MediaPlayer.create(this, R.raw.success);
			}else{
				mediaPlayer = MediaPlayer.create(this, R.raw.error);
			}
			mediaPlayer.stop();
			mediaPlayer.prepare();
			mediaPlayer.start();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	private boolean touchEvent(View v){
		Switch buttonView=(Switch)v;
		RelativeLayout rl=(RelativeLayout)buttonView.getParent().getParent();
		BootstrapEditText binedit=(BootstrapEditText)rl.findViewById(R.id.binedit);
		BootstrapEditText qtyedit=(BootstrapEditText)rl.findViewById(R.id.qtyedit);
		TextView seqhao=(TextView)rl.findViewById(R.id.id);
		if(!buttonView.isChecked()){//下一个状态
			if(StringUtil.isEmpty(binedit.getText()+"")||StringUtil.isEmpty(qtyedit.getText()+"")||"0".equals(qtyedit.getText()+"")){
				Toast.makeText(BackbinActivity.this, "请先完成数量(大于0)和仓位号", Toast.LENGTH_LONG).show();
				play_sound(false);
				return true;//错误就没有状态了
			}else{
				try {
					InbItemSub iis=db.findFirst(Selector.from(InbItemSub.class).where("id", "=", (seqhao.getText()+"").trim()));
					iis.setSTOBIN((binedit.getText()+"").toUpperCase(Locale.US).trim());
					binedit.setText(iis.getSTOBIN());
					iis.setQTY(Integer.parseInt(qtyedit.getText()+""));
					iis.setCheckQTY(true);
					db.update(iis, "stobin","qty","checkqty");
					play_sound(true);
					binedit.setEnabled(false);
					qtyedit.setEnabled(false);
					rl.setBackgroundResource(R.drawable.item_bg_green1);
					refreshTotal();
					productnoedit.requestFocus();
				} catch (DbException e) {
					e.printStackTrace();
				}
			}
		}else{
			try {
				InbItemSub iis=db.findFirst(Selector.from(InbItemSub.class).where("id", "=", (seqhao.getText()+"").trim()));
				iis.setCheckQTY(false);
				db.update(iis,"checkqty");
				play_sound(true);
				binedit.setEnabled(true);
				qtyedit.setEnabled(true);
				rl.setBackgroundResource(R.drawable.item_bg_blue);
				refreshTotal();
			} catch (DbException e) {
				e.printStackTrace();
			}
		}
		return false;
	}
}